package com.xxmw.transaction.common.utils;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

/**
 * 对称加密管理类
 */
public class AESHelper {
    private static final String IV_STRING_32 = "A-32-Byte-String";
    public static final String IV_STRING_16 = "A-16-Byte-String";
    private static final String charset = "UTF-8";
    private static final String key = "MIICcwIBADANBgkqhkiG9w0BAQEFAASC";

    public static String aesEncryptString(String content) throws Exception{
        byte[] contentBytes = content.getBytes(charset);
        byte[] keyBytes = key.getBytes(charset);
        byte[] encryptedBytes = aesEncryptBytes(contentBytes, keyBytes,IV_STRING_32);
        Base64.Encoder encoder = Base64.getEncoder();
        return encoder.encodeToString(encryptedBytes);
    }

    public static String aesEncryptString(String content,String key,String ivString) throws Exception{
        byte[] contentBytes = content.getBytes(charset);
        byte[] keyBytes = key.getBytes(charset);
        byte[] encryptedBytes = aesEncryptBytes(contentBytes, keyBytes,ivString);
        Base64.Encoder encoder = Base64.getEncoder();
        return encoder.encodeToString(encryptedBytes);
    }

    public static String aesDecryptString(String content) throws Exception{
        Base64.Decoder decoder = Base64.getDecoder();
        byte[] encryptedBytes = decoder.decode(content);
        byte[] keyBytes = key.getBytes(charset);
        byte[] decryptedBytes = aesDecryptBytes(encryptedBytes, keyBytes,IV_STRING_32);
        return new String(decryptedBytes, charset);
    }

    public static byte[] aesEncryptBytes(byte[] contentBytes, byte[] keyBytes,String ivString) throws Exception{
        return cipherOperation(contentBytes, keyBytes, Cipher.ENCRYPT_MODE,ivString);
    }

    public static byte[] aesDecryptBytes(byte[] contentBytes, byte[] keyBytes,String ivString) throws Exception{
        return cipherOperation(contentBytes, keyBytes, Cipher.DECRYPT_MODE,ivString);
    }

    private static byte[] cipherOperation(byte[] contentBytes, byte[] keyBytes, int mode,String ivString) throws Exception {
        SecretKeySpec secretKey = new SecretKeySpec(keyBytes, "AES");

        byte[] initParam = ivString.getBytes(charset);
        IvParameterSpec ivParameterSpec = new IvParameterSpec(initParam);

        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(mode, secretKey, ivParameterSpec);

        return cipher.doFinal(contentBytes);
    }

    public static void main(String[] args){
        try {
            String str=  aesEncryptString("112233");
            System.out.println(str);
            System.out.println(""+aesDecryptString(str));
        }catch (Exception e){
            e.printStackTrace();
        }

    }

}